from django.shortcuts import render,redirect,HttpResponse
from django.core.exceptions import ValidationError
from django import forms
from io import BytesIO

from app03.utils.code import check_code
from app03 import models

from app03.utils.encrypt import md5
from app03.utils.bootrsap import BootrsapForm

#创建一个用于登录的Form表单类
class LoginForm(BootrsapForm):
    user_n=forms.CharField(
        label='管理员',
        widget=forms.TextInput(attrs={"class": "form-control"}),
        # 不能为空
        required=True
    )
    password= forms.CharField(
        label='密码',
        widget=forms.PasswordInput( attrs={"class": "form-control"} ),
        # 不能为空
        required=True
    )
    code=forms.CharField(
        label='验证码',
        widget=forms.TextInput,
        required=True
    )
    #给密码加密
    def clean_password(self):
        pwd=self.cleaned_data.get('password')
        return md5(pwd)
#登录
def login_dl(request):

    if request.method=='GET':
        form = LoginForm()
        return render(request,'account_dl.html',{'form':form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # form.cleaned_data={'username': 'tbfaj864', 'password': 'cb68dabb852f388164f69156295dd297',code}

        #验证验证码
        # 将数组中的验证码剔除并返回验证码
        user_input_code=form.cleaned_data.pop('code')
        codes=request.session.get('image_code')

        # 当生成的验证码不等于用户输入的验证码时 将报错内容返回
        if codes != user_input_code:
            form.add_error( 'code', '验证码错误' )
            return render( request, 'account_dl.html', {'form': form} )


        # 获取到的数据去到数据库中校验
        admin_object=models.Admins.objects.filter(**form.cleaned_data).first()
        #当获取到的数据为none
        if not admin_object:
            form.add_error('password','账户名或密码错误')
            return render(request, 'account_dl.html', {'form': form} )
        #用户名跟密码正确
        request.session['info']={'id':admin_object.id,'name':admin_object.user_n}
        # request.session['image']=str({'img':admin_object.img})
        # print(request.session['image'])
        # session保存7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/admin/list/')
    return render( request, 'account_dl.html', {'form': form} )

def image_code(request):

    #调用check_code生成随机验证码
    img,code_string=check_code()
    #写入到session中(以便后面验证码校验)
    request.session['image_code']=code_string
    # 设置session超时60s
    request.session.set_expiry(60)
    # 将生成的图片保存到文件中
    stream = BytesIO()
    img.save( stream, 'png' )
    return HttpResponse(stream.getvalue())

#注销
def logout(request):

    request.session.clear()
    return redirect('/login/')

#注册
def login_zc(request):

    if request.method=='GET':
        form=LoginForm()
        return render(request,'account_zc.html',{'form':form})
    form=LoginForm(data=request.POST)
    if form.is_valid():
        # 验证验证码
        # 将数组中的验证码剔除并返回验证码
        user_input_code=form.cleaned_data.pop('code')
        codes=request.session.get('image_code')

        #当用户输入的验证码不等于随机生成验证码的时候,将错误返回
        if codes != user_input_code:
            form.add_error( 'code', '验证码错误' )
            return render(request,'account_zc.html',{'form':form})

        admins_exitis=models.Admins.objects.filter(**form.cleaned_data).exists()
        #将数据与数据库进行效验，如果存在则提示错误，不存在则存取到数据库中
        if admins_exitis:
            form.add_error('user_n', '账户名已存在' )
            return render( request, 'account_zc.html', {'form': form} )
        models.Admins.objects.create(**form.cleaned_data)
        return redirect('/login/')
    return render(request,'account_zc.html',{'form':form})